package com.liu.serialization;


import com.liu.serialization.impl.JSONType;

import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 序列化器管理
 */
public final class SerializationProvider {

    private static volatile SerializationProvider serializationProvider;

    private static final CopyOnWriteArrayList<Serialization> serializations=new CopyOnWriteArrayList<>();

    private SerializationProvider() {
        registerSerialization(new JSONType());
    }

    public static boolean registerSerialization(Serialization serialization){
        return serializations.add(serialization);
    }

    // 根据解码后的消息，在工厂类处理器中查找可以处理当前消息的处理器
    public static Serialization getSerialization(SerializationTypeEnum serializationType) {
        getInstance();
        for (Serialization serialization : serializations) {
            if (serialization.support(serializationType)) {
                return serialization;
            }
        }
        throw new RuntimeException("cannot find resolver, message type");
    }

    private static void getInstance() {
        if (serializationProvider==null){
            synchronized (SerializationProvider.class){
                if (serializationProvider==null){
                    serializationProvider=new SerializationProvider();
                }
            }
        }
    }

}